package com.banmao.youZone.entity;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Slf4j
@Data
@TableName("holiday")
public class Holiday {

    @TableId(value = "id", type = IdType.ASSIGN_UUID)
    private String id;

    @TableField("isHoliday")
    private Boolean holiday;

    @TableField("name")
    private String name;

    @TableField("date")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    private Date date;

    @TableField("year")
    private String year;

    public static List<Holiday> build(String json) {
        JSONObject resp = JSON.parseObject(json);
        if (!resp.containsKey("code") || !resp.containsKey("holiday"))  {
            log.error("[获取节假日]请求数据失败");
            return Collections.emptyList();
        }

        String thisYear = String.valueOf(DateUtil.date().year());

        ArrayList<Holiday> holidays = new ArrayList<>();
        JSONObject holidayObj = (JSONObject) resp.get("holiday");
        for (Object value : holidayObj.values()) {
            JSONObject v = (JSONObject)  value;
            Holiday holidayT = JSON.parseObject(v.toString(), Holiday.class);
            holidayT.setYear(thisYear);
            holidays.add(holidayT);
        }

        if (holidays.isEmpty()) {
            return Collections.emptyList();
        }

        return holidays;
    }

}
